/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EdicaoProd.java
 *
 * Created on 04/12/2009, 13:18:33
 */

package sigbar.view;

import sigbar.access.BDInterface;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 *
 * @author Hudson
 */
public class EdicaoProd extends javax.swing.JDialog {

    int registro;
    boolean edicao;
    int linhasel;
    BDInterface bcon;

    /** Creates new form EdicaoProd */
    public EdicaoProd(java.awt.Frame parent, boolean modal, BDInterface bcon) {
        super(parent, modal);
        initComponents();
        init();
        setBcon(bcon);
        PopularTabela();
    }

    public BDInterface getBcon() {
        return bcon;
    }

    public void setBcon(BDInterface bcon) {
        this.bcon = bcon;
    }

    private void PopularTabela() {
        Vector<Vector<String>> produtos = bcon.buscarProdutos();
        DefaultTableModel modelo = (DefaultTableModel) tableProd.getModel();
        for ( int i = 0; i < produtos.size(); i++ ) {
            if ( i >= modelo.getRowCount() ) {
                modelo.addRow(new Object[]{null,null});
            }
            modelo.setValueAt(produtos.get(i).get(0), i, 0);
            modelo.setValueAt(produtos.get(i).get(1), i, 1);
            modelo.setValueAt(produtos.get(i).get(2), i, 2);
            modelo.setValueAt(produtos.get(i).get(3), i, 3);
            modelo.setValueAt(produtos.get(i).get(4), i, 4);
        }
    }

    private void init() {
        registro = 0;
        edicao = false;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tableProd = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        textfieldNome = new javax.swing.JTextField();
        textfieldValVenda = new javax.swing.JTextField();
        textfieldValCompra = new javax.swing.JTextField();
        textfieldLimit = new javax.swing.JTextField();
        textfieldQnt = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        buttonLocal = new javax.swing.JButton();
        buttonCadastro = new javax.swing.JButton();
        buttonRemover = new javax.swing.JButton();
        buttonEditar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Editar Produtos");
        setResizable(false);

        tableProd.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Nome", "Valor Venda", "Valor Compra", "Limite", "Quantidade"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true, false, true, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tableProd);

        jLabel1.setText("Cadastro de Produto");

        jLabel2.setText("Nome:");

        jLabel3.setText("Valor Venda:");

        jLabel4.setText("Valor Compra:");

        jLabel5.setText("Limite:");

        jLabel6.setText("Quantidade:");

        jPanel2.setLayout(new java.awt.BorderLayout());

        buttonLocal.setText("Localizar");
        buttonLocal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonLocalActionPerformed(evt);
            }
        });
        jPanel2.add(buttonLocal, java.awt.BorderLayout.CENTER);

        buttonCadastro.setText("Cadastrar Produto");
        buttonCadastro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCadastroActionPerformed(evt);
            }
        });
        jPanel2.add(buttonCadastro, java.awt.BorderLayout.PAGE_START);

        buttonRemover.setText("Remover Produto");
        buttonRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonRemoverActionPerformed(evt);
            }
        });
        jPanel2.add(buttonRemover, java.awt.BorderLayout.PAGE_END);

        buttonEditar.setText("Editar");
        buttonEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonEditarActionPerformed(evt);
            }
        });
        jPanel2.add(buttonEditar, java.awt.BorderLayout.LINE_START);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textfieldNome, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textfieldValVenda, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textfieldValCompra, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textfieldLimit, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textfieldQnt, javax.swing.GroupLayout.DEFAULT_SIZE, 74, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(textfieldNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(textfieldValVenda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(textfieldValCompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(textfieldLimit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(textfieldQnt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(120, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 454, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE))
                .addGap(27, 27, 27))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonCadastroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCadastroActionPerformed
        if ( !(edicao) ) {
            if (textfieldNome.getText().equals("") ) {
                JOptionPane.showMessageDialog(this, "Nome de Produto inválido, digite novamente");
            }
            else {
                try {
                DefaultTableModel modelo = (DefaultTableModel) tableProd.getModel();
                modelo.addRow(new Object[]{null,null});
                modelo.setValueAt(textfieldNome.getText(), registro, 0);
                if ( !(textfieldValVenda.getText().equals("")) ) {
                    modelo.setValueAt(textfieldValVenda.getText(), registro, 1);
                }
                else {
                    modelo.setValueAt(0, registro, 1);
                }
                if ( !(textfieldValCompra.getText().equals("")) ) {
                    modelo.setValueAt(textfieldValCompra.getText(), registro, 2);
                }
                else {
                    modelo.setValueAt(0, registro, 2);
                }
                if ( !(textfieldLimit.getText().equals("")) ) {
                    modelo.setValueAt(textfieldLimit.getText(), registro, 3);
                }
                else {
                    modelo.setValueAt(0, registro, 3);
                }
                if ( !(textfieldQnt.getText().equals("")) ) {
                    modelo.setValueAt(textfieldQnt.getText(), registro, 4);
                }
                else {
                    modelo.setValueAt(0, registro, 4);
                }
                // Colocando no Banco de Dados
                Double vc = (Double)modelo.getValueAt(registro, 2);
                Integer lim = (Integer)modelo.getValueAt(registro, 3);
                Double vv = (Double)modelo.getValueAt(registro, 1);
                Integer qnt = (Integer)modelo.getValueAt(registro, 4);
                String nom = modelo.getValueAt(registro, 0).toString();
                bcon.cadastrarProduto( nom, vc, lim, vv, qnt);

                registro = registro + 1;
                }
                catch (Exception ex) {
                    System.out.println(ex.getMessage());
                    JOptionPane.showMessageDialog(this, "Não foi possível cadastrar o produto no banco de dados");
                }
            }
        }
        else {
            if (textfieldNome.getText().equals("") ) {
                JOptionPane.showMessageDialog(this, "Nome de Produto inválido, digite novamente");
            }
            else {
                try {
                    DefaultTableModel modelo = (DefaultTableModel) tableProd.getModel();
                    String nomeantigo = modelo.getValueAt(linhasel, 0).toString();
                    modelo.setValueAt(textfieldNome.getText(), linhasel, 0);
                    if ( !(textfieldValVenda.getText().equals("")) ) {
                        modelo.setValueAt(textfieldValVenda.getText(), linhasel, 1);
                    }
                    else {
                        modelo.setValueAt(0, linhasel, 1);
                    }
                    if ( !(textfieldValCompra.getText().equals("")) ) {
                        modelo.setValueAt(textfieldValCompra.getText(), linhasel, 2);
                    }
                    else {
                        modelo.setValueAt(0, linhasel, 2);
                    }
                    if ( !(textfieldLimit.getText().equals("")) ) {
                        modelo.setValueAt(textfieldLimit.getText(), linhasel, 3);
                    }
                    else {
                        modelo.setValueAt(0, linhasel, 3);
                    }
                    if ( !(textfieldQnt.getText().equals("")) ) {
                        modelo.setValueAt(textfieldQnt.getText(), linhasel, 4);
                    }
                    else {
                        modelo.setValueAt(0, linhasel, 4);
                    }
                    Double vc = (Double)modelo.getValueAt(linhasel, 2);
                    Integer lim = (Integer)modelo.getValueAt(linhasel, 3);
                    Double vv = (Double)modelo.getValueAt(linhasel, 1);
                    Integer qnt = (Integer)modelo.getValueAt(linhasel, 4);
                    String nom = modelo.getValueAt(linhasel, 0).toString();
                    bcon.atualizarProduto(nomeantigo, nom, vc, lim, vv, qnt);
                }
                catch (Exception ex) {
                    System.out.println(ex.getMessage());
                    JOptionPane.showMessageDialog(this, "Não foi possível atualizar o produto no banco de dados");
                }
            }
            textfieldNome.setText("");
            textfieldValVenda.setText("");
            textfieldValCompra.setText("");
            textfieldLimit.setText("");
            textfieldQnt.setText("");
            buttonCadastro.setText("Cadastrar Produto");
            buttonRemover.setText("Remover Produto");
            buttonEditar.setEnabled(true);
            buttonLocal.setEnabled(true);
            tableProd.setEnabled(true);
            edicao = false;
        }
}//GEN-LAST:event_buttonCadastroActionPerformed

    private void buttonRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRemoverActionPerformed
        if ( !(edicao) ) {
            int[] l = tableProd.getSelectedRows();//captura as linhas selecionadas
            if ( l.length != 0 ) {
                DefaultTableModel modelo = (DefaultTableModel) tableProd.getModel();
                for(int i = (l.length-1); i >= 0; --i) {
                    modelo.removeRow(l[i]);//remove todas as linhas selecionadas
                }
                tableProd.setModel(modelo);
                registro = registro - l.length;
                if ( registro < 0 ) {
                    registro = 0;
                }
            } else {
                JOptionPane.showMessageDialog(this,"Selecione uma linha da tabela para Remover");
            }
        }
        else {
            textfieldNome.setText("");
            textfieldValVenda.setText("");
            textfieldValCompra.setText("");
            textfieldLimit.setText("");
            textfieldQnt.setText("");
            buttonCadastro.setText("Cadastrar Produto");
            buttonRemover.setText("Remover Produto");
            buttonEditar.setEnabled(true);
            buttonLocal.setEnabled(true);
            tableProd.setEnabled(true);
            edicao = false;
        }
    }//GEN-LAST:event_buttonRemoverActionPerformed

    private void buttonEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonEditarActionPerformed
        int[] l = tableProd.getSelectedRows();//captura as linhas selecionadas
        if ( l.length > 1 ) {
            JOptionPane.showMessageDialog(this, "Selecione somente um Produto para Editar");
        }
        else {
            if ( l.length == 0 ) {
                JOptionPane.showMessageDialog(this, "Selecione um Produto para Editar");
            }
            else {
                textfieldNome.setText((String)tableProd.getValueAt(l[0], 0));
                textfieldValVenda.setText((String)tableProd.getValueAt(l[0], 1));
                textfieldValCompra.setText((String)tableProd.getValueAt(l[0], 2));
                textfieldLimit.setText((String)tableProd.getValueAt(l[0], 3));
                textfieldQnt.setText((String)tableProd.getValueAt(l[0], 4));
                buttonCadastro.setText("Confirmar Edição");
                buttonRemover.setText("Cancelar Edição");
                buttonEditar.setEnabled(false);
                buttonLocal.setEnabled(false);
                tableProd.setEnabled(false);
                linhasel = l[0];
                edicao = true;
            }
        }
    }//GEN-LAST:event_buttonEditarActionPerformed

    private void buttonLocalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLocalActionPerformed
        ListSelectionModel selecao = tableProd.getSelectionModel();
        selecao.clearSelection();
        TableModel modelotab = tableProd.getModel();
        ArrayList<Integer> selecionados = new ArrayList<Integer>();

        // Ver se tem alguma coisa escrita no campo Nome para localizar
        if ( !(textfieldNome.getText().equals("")) ) {
            for (int i = 0; i < modelotab.getRowCount(); i++ ) {
                if ( textfieldNome.getText().equals(modelotab.getValueAt(i, 0)) ) {
                    if ( !selecionados.contains(i)) {
                        selecionados.add(i);
                    }
                }
                else {
                    if ( selecionados.contains(i) ) {
                        selecionados.remove((Object)i);
                    }
                }
            }
        }
        else {
            JOptionPane.showMessageDialog(this, "Escreva o Nome do Produto que deseja buscar");
        }

        // Seleciona o resultado
        if ( selecionados.size() == 0 ) {
            JOptionPane.showMessageDialog(this, "Não foi encontrada nenhum registro do Produto procurado");
        } else {
            for (int i = 0; i < selecionados.size(); i++) {
                selecao.addSelectionInterval(selecionados.get(i), selecionados.get(i));
            }
        }
    }//GEN-LAST:event_buttonLocalActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCadastro;
    private javax.swing.JButton buttonEditar;
    private javax.swing.JButton buttonLocal;
    private javax.swing.JButton buttonRemover;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tableProd;
    private javax.swing.JTextField textfieldLimit;
    private javax.swing.JTextField textfieldNome;
    private javax.swing.JTextField textfieldQnt;
    private javax.swing.JTextField textfieldValCompra;
    private javax.swing.JTextField textfieldValVenda;
    // End of variables declaration//GEN-END:variables

}
